# -*- coding: utf-8 -*-
"""
@Time : 2024/10/17 20:46
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : monitor_weibo_user.py
"""

import json
import logging
import sys
from urllib.parse import quote

import requests
from bs4 import BeautifulSoup

from sys_func.read_config import load_yaml

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='monitor.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()


def get_sub_cookie():
    session = requests.Session()
    session_url = """
    https://login.sina.com.cn/visitor/visitor?a=crossdomain&s=_2AkMeUW2sdcPxrAJZmv8WyWvhaolH-jythARaAn7uJhMyOhh87goXqSdutBF-XKZoH7j4qHcFNgZse15cS9tih-UG&sp=0033WrSXqPxfM72wWs9jqgMF55529P9D9WFmpDoV36wskXrwCOfoDO7o5JpVhsfD9sxj9gUa9FR3Zntt&from=weibo&_rand=0.5841943882049672&entry=miniblog&url=https%3A%2F%2Fweibo.com%2Flogin.php%3Furl%3Dhttps%253A%252F%252Fweibo.com%252Fnewlogin%253Ftabtype%253Dlist%2526gid%253D1028039999%2526openLoginLayer%253D0%2526url%253Dhttps%25253A%25252F%25252Fweibo.com%25252F
    """
    session.get(session_url, headers={"referer": "https://passport.weibo.com/",
                                      "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"})
    # cookie_sub = session.cookies.get_dict()
    # print(cookie_sub)
    cookie_sub = session.cookies.get_dict().get("SUB")
    if len(cookie_sub) >= 10:
        sub_info = "SUB=" + cookie_sub + ";"
    else:
        # 获取配置文件中的页数配置值
        config_data = load_yaml('config_monitor.yaml')
        sub_info = config_data.get('weibo').get('cookie_sub')
    return sub_info


# logger.info(f"监控微博用户monitor_weibo_user过程中获取到的cookie sub的值：{get_sub_cookie()}")


def get_userid_by_name(name, sub_info):
    """
    通过用户名获取用户id
    :param name: 用户名
    :param sub_info: cookie中的SUB信息
    :return: 用户id
    """
    user_encode = quote(name)

    url = f'https://s.weibo.com/user?q={user_encode}'
    referer = f'https://s.weibo.com/weibo?q={user_encode}'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Referer": referer,
        # "Cookie": "SUB=_2AkMRBb7odcPxrAJZmv8WyWvhaolH-jyi0NceAn7uJhMyOhh87mYkqSdutBF-XAHavRIYgFDYmUOPezr3SUzDg2yl"}
        "Cookie": f"{sub_info}"}
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser')
    user_ls = soup.find(class_='card-wrap').find_all(class_='card')

    user_result = []
    target_user_id = ''
    for user in user_ls:
        user_name = user.find(class_='name').text
        user_id = user.find(class_='name').get('href').split('/')[-1]
        profile = user.find(class_='info').find_all('p')[0].text if len(
            user.find(class_='info').find_all('p')) > 1 else None
        follower = user.find(class_='s-nobr').text

        user_result.append({"name": user_name, "user_id": user_id, "profile": profile, "follower": follower})

        if user_name == name:
            target_user_id = user_id

    print(f"{name}对应id：{target_user_id}\n")
    logger.info(f"{name}对应id：{target_user_id}\n")
    return target_user_id


def get_mblog(uid, top_n, sub_info):
    """
    获取特定用户的微博博文数据
    :param uid: 用户id
    :param top_n: 微博分页数
    :param sub_info: cookie中的SUB信息
    :return: 返回微博数据列表
    """
    # 爬取结果
    target = []

    for i in range(1, top_n + 1):
        url = f"https://weibo.com/ajax/statuses/mymblog?uid={uid}&page={i}&feature=0"
        logger.info(f"{__name__}方法收到的cookie信息sub值{sub_info}")
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Cookie": f"XSRF-TOKEN=b6kfMBNz4q5N5e34n_vlObjj; {sub_info}",
            "referer": f"https://weibo.com/u/{uid}",
            "x-xsrf-token": "b6kfMBNz4q5N5e34n_vlObjj",
            # "Cookie": """SCF=Am07ajJTOeaduGrhlixMpwPoTIii5XXdcG60cqDAmzA0-Ihps3p71qAXLpw-VsOtof4OStClm-eKRO2GhV2rpwE.; SINAGLOBAL=2365547455307.967.1753108724931; UOR=,,no18.fun; SUB=_2A25FuoQ_DeRhGedG6VUS9S7PzTiIHXVmuZn3rDV8PUNbmtANLW3QkW9NUXc-K16GBrlcfYLLDgV5qEuy5lw0J1wd; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFmpDoV36wskXrwCOfoDO7o5NHD95Qp1hzNe0-7e0qXWs4DqcjVi--4i-2fiK.fi--4i-2Xi-88i--ci-zfi-zNPEH81CHFBb-4eCH8SC-4xb-4xntt; ALF=02_1759936879; webim_unReadCount=%7B%22time%22%3A1757670348920%2C%22dm_pub_total%22%3A0%2C%22chat_group_client%22%3A0%2C%22chat_group_notice%22%3A0%2C%22allcountNum%22%3A0%2C%22msgbox%22%3A0%7D; _s_tentry=no18.fun; Apache=4015353736527.15.1757720320300; ULV=1757720320305:44:7:5:4015353736527.15.1757720320300:1757677929644; XSRF-TOKEN=uCcc8lSUuikfQrIagnmAXR4p; WBPSESS=Dt2hbAUaXfkVprjyrAZT_LiUiW8SXDTeScMiET2SIh1C5ev9bZEZ3dCACsHNDr7cOLgxHZxoHDWEW-8DO8CXaG6rzyVVbbkfay-UYkpXd68ruQReNnI5SZPYckkqYdF6XRioKzKUqmtjoAj-xuNjLD5WIcnw7YlUOyDVzFvwGcP2JzOU8IGqJIpFo9LD9SInU72RgCu8-ky7-LQ_junWjw=="""
        }
        # print(headers)
        r = requests.get(url, headers=headers)
        # print(r)
        # print(r.text)
        try:
            data = json.loads(r.text)
            # print("dsds",data)
        except Exception as e:
            logger.info(f"发生异常{e.__class__.__name__}，退出执行，需要替换请求headers中Cookie的SUB值"
                        f"SUB位置：浏览器F12打开开发者工具，应用-存储-Cookie，找Domain域名是.weibo.com的名称SUB的值替换。")
            # sys.exit(f"发生异常{e.__class__.__name__}，退出执行，需要替换请求headers中Cookie的SUB值"
            #          f"SUB位置：浏览器F12打开开发者工具，应用-存储-Cookie，找Domain域名是.weibo.com的名称SUB的值替换。")
            return
        # print(data)
        blogs = data.get("data").get("list")
        # print(blogs)

        for blog in blogs:
            if 'isTop' not in blog:
                target.append({"text": blog.get("text_raw"), "address_site": blog.get("region_name"),
                               "publish_time": blog.get("created_at"), "mblogid": blog.get("mblogid"),
                               "is_long_text": blog.get("isLongText")})

    return target


def get_mblog_long_text(user_id, mblog_id, sub_info):
    """
    通过微博id获取微博完整文本
    :param mblog_id:
    :param sub_info: cookie中的SUB信息
    :return:
    """
    logger.info(f"传入的微博id：{mblog_id}")
    url = f"https://weibo.com/ajax/statuses/longtext?id={mblog_id}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Cookie": f"{sub_info}",
        "referer": f"https://weibo.com/{user_id}"
    }
    resp = requests.get(url, headers=headers).json()
    # print(resp)
    # logger.info(f"get_mblog_long_text获取到的数据：{resp}")
    mblog_longtext = resp.get("data").get("longTextContent")
    logger.info(f"微博完整文本：{mblog_longtext}")
    # print(resp.get("data").get("longTextContent"))
    return mblog_longtext


if __name__ == '__main__':
    sub_info = get_sub_cookie()
    # get_userid_by_name("国家图书馆")
    # r = get_mblog_long_text("6124869582", "Q4laMavVc", sub_info)
    # print(r)
    # print(sub_info)
    print(get_mblog("1929520707", 1, sub_info))
